const app = getApp()

// 添加健康评分相关的辅助函数
const getHealthStatus = (score) => {
  if (score >= 90) return { text: '优秀', color: '#4ade80' }  // 翠绿色
  if (score >= 70) return { text: '良好', color: '#86efac' }  // 浅绿色
  if (score >= 50) return { text: '一般', color: '#fcd34d' }  // 橙黄色
  return { text: '需注意', color: '#f87171' }  // 红色
}

// 计算健康评分
const calculateHealthScore = (records) => {
  if (!records || records.length === 0) return 0
  const normalCount = records.filter(record => {
    return record.typeId === '1' || record.typeId === 1  // 同时检查字符串和数字类型
  }).length
  return Math.round((normalCount / records.length) * 100)
}

Page({
  data: {
    reportType: '', // 报告类型：daily, weekly, monthly, yearly
    reportTitle: '', // 报告标题
    canvasReady: false, // 添加画布准备状态
    showLoading: false, // 添加loading状态
  },

  onLoad(options) {
    // 只设置初始数据
    this.setData({
      reportType: options.type || 'daily',
      reportTitle: options.title || '健康报告',
      canvasReady: false,
      showLoading: false
    })
  },

  // 页面显示后再生成报告
  onReady() {
    // 显示loading
    this.setData({
      showLoading: true
    })
    
    // 使用 nextTick 确保在页面完全渲染后再生成报告
    wx.nextTick(() => {
      this.generateReport()
    })
  },

  async generateReport() {
    try {
      // 获取canvas上下文
      const query = wx.createSelectorQuery()
      const canvasNode = await new Promise((resolve, reject) => {
        query.select('#reportCanvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            if (!res || !res[0] || !res[0].node) {
              reject(new Error('Canvas node not found'))
              return
            }
            resolve(res[0].node)
          })
      })

      const ctx = canvasNode.getContext('2d')
      
      // 获取设备信息
      const systemInfo = wx.getSystemInfoSync()
      const dpr = systemInfo.pixelRatio || 1
      const screenWidth = systemInfo.screenWidth
      
      // 设置canvas尺寸
      const canvasWidth = screenWidth * dpr * 0.9
      const canvasHeight = canvasWidth * 1.4
      
      // 设置canvas的实际渲染尺寸
      canvasNode.width = canvasWidth
      canvasNode.height = canvasHeight

      // 缩放上下文以适应 DPR
      ctx.scale(dpr, dpr)

      // 保存实际绘制尺寸到ctx对象
      ctx._width = canvasWidth / dpr
      ctx._height = canvasHeight / dpr

      // 根据报告类型调用对应的绘制函数
      switch (this.data.reportType) {
        case 'daily':
          await this.drawDailyReport(ctx)
          break
        case 'weekly':
          await this.drawWeeklyReport(ctx)
          break
        case 'monthly':
          await this.drawMonthlyReport(ctx)
          break
        case 'yearly':
          await this.drawYearlyReport(ctx)
          break
      }

      // 画布准备完成后，显示画布并隐藏loading
      this.setData({
        canvasReady: true,
        showLoading: false
      })
    } catch (error) {
      // 静默处理生成报告失败
      this.setData({
        showLoading: false
      })
      this.selectComponent('#customToast').showToast('生成报告失败')
    }
  },

  // 绘制日报
  async drawDailyReport(ctx) {
    const width = ctx._width
    const height = ctx._height
    const padding = width * 0.08
    
    // 绘制背景
    ctx.fillStyle = '#e8f4f8'  // 使用浅蓝色背景
    ctx.fillRect(0, 0, width, height)
    
    // 绘制主卡片背景
    const cardPadding = padding * 0.5
    ctx.fillStyle = '#ffffff'
    this.drawRoundedRect(ctx, cardPadding, cardPadding, width - cardPadding * 2, height - cardPadding * 2, 20)
    ctx.fill()
    
    // 绘制标题
    const titleY = padding * 2
    ctx.fillStyle = '#333333'
    ctx.font = `bold ${Math.floor(width * 0.08)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText(this.data.reportTitle, width / 2, titleY)

    // 绘制日期
    const dateY = titleY + padding * 0.8
    ctx.fillStyle = '#666666'
    ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
    ctx.fillText(new Date().toLocaleDateString('zh-CN'), width / 2, dateY)

    // 获取今日数据
    const today = new Date()
    const todayStr = this.formatDate(today)
    const todayRecords = (app.globalData.records || []).filter(record => record.date === todayStr)

    // 计算健康评分
    const healthScore = calculateHealthScore(todayRecords)
    const healthStatus = getHealthStatus(healthScore)

    // 绘制主要统计数据（排便次数和健康评分）
    const statsY = dateY + padding * 2
    const statsBoxHeight = height * 0.18
    const statsBoxWidth = (width - padding * 3) / 2

    // 绘制左侧统计框
    ctx.fillStyle = '#f8f8f8'
    this.drawRoundedRect(ctx, padding, statsY, statsBoxWidth, statsBoxHeight, 15)
    
    // 绘制右侧统计框
    this.drawRoundedRect(ctx, width - padding - statsBoxWidth, statsY, statsBoxWidth, statsBoxHeight, 15)

    // 绘制排便次数
    ctx.textAlign = 'center'
    ctx.fillStyle = '#4CAF50'  // 使用更柔和的绿色
    ctx.font = `bold ${Math.floor(width * 0.12)}px sans-serif`
    ctx.fillText(todayRecords.length.toString(), padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#666666'
    ctx.font = `${Math.floor(width * 0.04)}px sans-serif`
    ctx.fillText('今日排便次数', padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制健康评分
    ctx.fillStyle = healthStatus.color
    ctx.font = `bold ${Math.floor(width * 0.12)}px sans-serif`
    ctx.fillText(healthScore.toString(), width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#666666'
    ctx.font = `${Math.floor(width * 0.04)}px sans-serif`
    ctx.fillText('健康评分 · ' + healthStatus.text, width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制时间分布图表背景
    const chartY = height - padding * 4 - height * 0.25
    const chartHeight = height * 0.25
    const chartWidth = width - padding * 2.4
    
    ctx.fillStyle = '#f8f8f8'
    this.drawRoundedRect(ctx, padding, chartY - padding, width - padding * 2, chartHeight + padding * 2, 15)

    // 绘制时间分布柱状图（移到底部）
    const timeGroups = [
      { name: '凌晨', color: '#fcd34d', count: 0 },  // 橙黄色（不太健康的时间）
      { name: '早上', color: '#4ade80', count: 0 },  // 翠绿色（最健康的时间）
      { name: '中午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '下午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '晚上', color: '#fcd34d', count: 0 }   // 橙黄色（不太健康的时间）
    ]

    // 统计各时间段的数量
    todayRecords.forEach(record => {
      const hour = new Date(record.date + ' ' + record.time).getHours()
      if (hour >= 0 && hour < 6) timeGroups[0].count++
      else if (hour >= 6 && hour < 11) timeGroups[1].count++
      else if (hour >= 11 && hour < 14) timeGroups[2].count++
      else if (hour >= 14 && hour < 18) timeGroups[3].count++
      else timeGroups[4].count++
    })

    // 找出最大值
    const maxCount = Math.max(...timeGroups.map(g => g.count), 1)

    // 绘制柱状图
    const barWidth = chartWidth / timeGroups.length * 0.6
    const barGap = chartWidth / timeGroups.length

    // 绘制网格线
    ctx.strokeStyle = '#e6e6e6'
    ctx.lineWidth = 1
    for (let i = 0; i <= 4; i++) {
      const y = chartY + chartHeight * (1 - i / 4)
      ctx.beginPath()
      ctx.moveTo(padding * 1.2, y)
      ctx.lineTo(width - padding * 1.2, y)
      ctx.stroke()
    }

    timeGroups.forEach((group, index) => {
      const barHeight = (group.count / maxCount) * chartHeight
      const x = padding * 1.2 + barGap * index + (barGap - barWidth) / 2
      const y = chartY + chartHeight - barHeight

      // 绘制柱子
      ctx.fillStyle = group.color
      ctx.beginPath()
      const radius = barWidth * 0.15
      ctx.moveTo(x + radius, y)
      ctx.lineTo(x + barWidth - radius, y)
      ctx.quadraticCurveTo(x + barWidth, y, x + barWidth, y + radius)
      ctx.lineTo(x + barWidth, y + barHeight - radius)
      ctx.quadraticCurveTo(x + barWidth, y + barHeight, x + barWidth - radius, y + barHeight)
      ctx.lineTo(x + radius, y + barHeight)
      ctx.quadraticCurveTo(x, y + barHeight, x, y + barHeight - radius)
      ctx.lineTo(x, y + radius)
      ctx.quadraticCurveTo(x, y, x + radius, y)
      ctx.closePath()
      ctx.fill()

      // 添加渐变效果
      const gradient = ctx.createLinearGradient(x, y, x, y + barHeight)
      gradient.addColorStop(0, group.color)
      gradient.addColorStop(1, group.color + 'aa') // 调整透明度，使颜色更柔和
      ctx.fillStyle = gradient
      ctx.fill()

      // 绘制数值
      if (group.count > 0) {
        ctx.fillStyle = '#6b4f3f' // 使用深棕色显示数字
        ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
        ctx.textAlign = 'center'
        ctx.fillText(group.count, x + barWidth / 2, y - 10)
      }

      // 绘制标签（时间段）
      ctx.fillStyle = '#6b4f3f' // 使用深棕色显示文字
      ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
      ctx.textAlign = 'center'
      // 增加米色描边使文字更清晰
      ctx.strokeStyle = '#fff9e9'
      ctx.lineWidth = 3
      ctx.strokeText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
      ctx.fillText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
    })

    // 绘制图表标题（移到底部）
    ctx.fillStyle = '#6b4f3f'
    ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText('时间分布', width / 2, chartY + chartHeight + 60)

    // 绘制装饰性图标
    this.drawDecorativeElements(ctx, width, height, padding)
  },

  // 添加绘制圆角矩形的辅助函数
  drawRoundedRect(ctx, x, y, width, height, radius) {
    ctx.beginPath()
    ctx.moveTo(x + radius, y)
    ctx.lineTo(x + width - radius, y)
    ctx.arcTo(x + width, y, x + width, y + radius, radius)
    ctx.lineTo(x + width, y + height - radius)
    ctx.arcTo(x + width, y + height, x + width - radius, y + height, radius)
    ctx.lineTo(x + radius, y + height)
    ctx.arcTo(x, y + height, x, y + height - radius, radius)
    ctx.lineTo(x, y + radius)
    ctx.arcTo(x, y, x + radius, y, radius)
    ctx.closePath()

    // 添加渐变背景
    const gradient = ctx.createLinearGradient(x, y, x, y + height)
    gradient.addColorStop(0, '#ffffff')
    gradient.addColorStop(1, '#f8f8f8')
    ctx.fillStyle = gradient

    // 添加多层阴影效果
    ctx.shadowColor = 'rgba(0, 0, 0, 0.05)'
    ctx.shadowBlur = 15
    ctx.shadowOffsetX = 0
    ctx.shadowOffsetY = 5
    ctx.fill()

    // 添加边框
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.05)'
    ctx.lineWidth = 1
    ctx.stroke()
    
    // 重置阴影
    ctx.shadowColor = 'transparent'
    ctx.shadowBlur = 0
    ctx.shadowOffsetX = 0
    ctx.shadowOffsetY = 0

    // 添加装饰性圆点
    const dotRadius = 2
    const dotSpacing = 20
    const dotColor = '#fad0c4'
    
    // 绘制四角装饰圆点
    ctx.fillStyle = dotColor
    ctx.beginPath()
    ctx.arc(x + radius, y + radius, dotRadius, 0, Math.PI * 2)
    ctx.fill()
    
    ctx.beginPath()
    ctx.arc(x + width - radius, y + radius, dotRadius, 0, Math.PI * 2)
    ctx.fill()
    
    ctx.beginPath()
    ctx.arc(x + radius, y + height - radius, dotRadius, 0, Math.PI * 2)
    ctx.fill()
    
    ctx.beginPath()
    ctx.arc(x + width - radius, y + height - radius, dotRadius, 0, Math.PI * 2)
    ctx.fill()
  },

  // 绘制装饰性元素
  drawDecorativeElements(ctx, width, height, padding) {
    // 绘制左上角和右上角的叶子装饰
    this.drawLeaf(ctx, padding, padding, 0, '#90EE90')  // 左上角绿叶
    this.drawLeaf(ctx, width - padding, padding, 1, '#98FB98')  // 右上角绿叶，移到最右边
    
    // 绘制左下角和右下角的花朵装饰
    this.drawFlower(ctx, padding + 20, height - padding - 20, '#FFB6C1')  // 左下角粉花
    this.drawFlower(ctx, width - padding - 20, height - padding - 20, '#FFC0CB')  // 右下角粉花
    
    // 添加装饰性波浪线
    this.drawWaveLine(ctx, padding, height - padding * 3, width - padding * 2, '#fad0c4')
  },

  // 添加波浪线装饰
  drawWaveLine(ctx, x, y, width, color) {
    ctx.beginPath()
    ctx.strokeStyle = color
    ctx.lineWidth = 2
    
    const amplitude = 10
    const frequency = 0.05
    
    ctx.moveTo(x, y)
    for (let i = 0; i <= width; i++) {
      ctx.lineTo(x + i, y + Math.sin(i * frequency) * amplitude)
    }
    
    ctx.stroke()
  },

  // 更新叶子绘制函数
  drawLeaf(ctx, x, y, direction, color) {
    ctx.save()
    ctx.translate(x, y)
    if (direction) ctx.scale(-1, 1)
    
    // 绘制主叶片
    ctx.beginPath()
    ctx.moveTo(0, 0)
    ctx.bezierCurveTo(10, -20, 40, -20, 40, 0)
    ctx.bezierCurveTo(40, 20, 10, 20, 0, 0)
    
    // 添加渐变效果
    const gradient = ctx.createLinearGradient(0, -20, 0, 20)
    gradient.addColorStop(0, color)
    gradient.addColorStop(1, color + '88')
    ctx.fillStyle = gradient
    ctx.fill()
    
    // 添加叶脉
    ctx.beginPath()
    ctx.moveTo(0, 0)
    ctx.quadraticCurveTo(20, 0, 40, 0)
    ctx.strokeStyle = '#ffffff88'
    ctx.lineWidth = 2
    ctx.stroke()
    
    // 添加次级叶脉
    for (let i = 1; i <= 3; i++) {
      ctx.beginPath()
      ctx.moveTo(i * 10, 0)
      ctx.quadraticCurveTo(i * 10 + 5, i * 3, i * 10 + 10, 0)
      ctx.stroke()
    }
    
    ctx.restore()
  },

  // 更新花朵绘制函数
  drawFlower(ctx, x, y, color) {
    ctx.save()
    ctx.translate(x, y)
    
    // 绘制花瓣
    for (let i = 0; i < 5; i++) {
      ctx.beginPath()
      ctx.ellipse(0, -15, 8, 15, (i * Math.PI * 2) / 5, 0, Math.PI * 2)
      
      // 添加渐变效果
      const gradient = ctx.createRadialGradient(0, -15, 0, 0, -15, 15)
      gradient.addColorStop(0, color)
      gradient.addColorStop(1, color + '88')
      ctx.fillStyle = gradient
      ctx.fill()
    }
    
    // 绘制花蕊
    ctx.beginPath()
    ctx.arc(0, 0, 8, 0, Math.PI * 2)
    const centerGradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 8)
    centerGradient.addColorStop(0, '#FFD700')
    centerGradient.addColorStop(1, '#FFA500')
    ctx.fillStyle = centerGradient
    ctx.fill()
    
    // 添加花蕊点缀
    for (let i = 0; i < 6; i++) {
      const angle = (i * Math.PI * 2) / 6
      const dotX = Math.cos(angle) * 4
      const dotY = Math.sin(angle) * 4
      ctx.beginPath()
      ctx.arc(dotX, dotY, 1.5, 0, Math.PI * 2)
      ctx.fillStyle = '#ffffff'
      ctx.fill()
    }
    
    ctx.restore()
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 计算平均时长
  calculateAverageDuration(records) {
    if (!records || records.length === 0) return 0
    const totalDuration = records.reduce((sum, record) => sum + (record.duration || 0), 0)
    return Math.round(totalDuration / records.length)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '我的健康报告，一起来记录吧！',
      path: '/packageA/pages/report/report',
      imageUrl: 'https://gitee.com/teajoy/image/raw/master/images/share-cover.png'
    }
  },

  // 用户点击右上角分享到朋友圈
  onShareTimeline() {
    return {
      title: this.data.reportTitle,
      query: `type=${this.data.reportType}`
    }
  },

  // 分享报告按钮点击事件
  handleShare() {
    this.selectComponent('#customToast').showToast('请点击右上角进行分享')
  },

  // 保存报告到相册
  async saveReport() {
    try {
      const query = wx.createSelectorQuery()
      const canvas = await new Promise((resolve) => {
        query.select('#reportCanvas')
          .fields({ node: true })
          .exec((res) => resolve(res[0].node))
      })

      const tempFilePath = await wx.canvasToTempFilePath({
        canvas: canvas
      })

      await wx.saveImageToPhotosAlbum({
        filePath: tempFilePath.tempFilePath
      })

      this.selectComponent('#customToast').showToast('保存成功')
    } catch (error) {
      // 静默处理保存报告失败
      this.selectComponent('#customToast').showToast('保存失败')
    }
  },

  // 绘制周报
  async drawWeeklyReport(ctx) {
    const width = ctx._width
    const height = ctx._height
    const padding = width * 0.08
    
    // 绘制背景
    ctx.fillStyle = '#e8f4f8'  // 使用浅蓝色背景
    ctx.fillRect(0, 0, width, height)
    
    // 绘制主卡片背景
    const cardPadding = padding * 0.5
    ctx.fillStyle = '#ffffff'
    this.drawRoundedRect(ctx, cardPadding, cardPadding, width - cardPadding * 2, height - cardPadding * 2, 20)
    ctx.fill()
    
    // 绘制标题
    const titleY = padding * 1.5
    const gradient = ctx.createLinearGradient(0, titleY - 30, 0, titleY)
    gradient.addColorStop(0, '#ff9a9e')
    gradient.addColorStop(1, '#fad0c4')
    ctx.fillStyle = gradient
    ctx.font = `bold ${Math.floor(width * 0.1)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText(this.data.reportTitle, width / 2, titleY)

    // 获取本周日期范围
    const today = new Date()
    const weekStart = new Date(today)
    // 获取当前是星期几(0-6, 0代表星期日)
    const currentDay = today.getDay()
    // 计算到本周一的偏移量，如果当前是周日(0)，需要往前推6天
    const mondayOffset = currentDay === 0 ? -6 : (1 - currentDay)
    weekStart.setDate(today.getDate() + mondayOffset) // 设置为本周一
    weekStart.setHours(0, 0, 0, 0) // 设置时间为当天开始
    
    const weekEnd = new Date(weekStart)
    weekEnd.setDate(weekStart.getDate() + 6) // 设置为本周日
    weekEnd.setHours(23, 59, 59, 999) // 设置时间为当天结束

    // 绘制日期范围
    const dateY = titleY + padding * 0.8
    ctx.fillStyle = '#666666'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText(`${this.formatDate(weekStart)} 至 ${this.formatDate(weekEnd)}`, width / 2, dateY)

    // 格式化日期函数
    const parseDate = (dateStr) => {
      const [year, month, day] = dateStr.split('-').map(Number)
      const date = new Date(year, month - 1, day)
      return date
    }

    // 获取本周数据
    const weekRecords = (app.globalData.records || []).filter(record => {
      if (!record.date) return false
      const recordDate = parseDate(record.date)
      return recordDate >= weekStart && recordDate <= weekEnd
    })

    // 添加调试日志
    // 处理周报数据

    // 计算健康评分
    const healthScore = calculateHealthScore(weekRecords)
    const healthStatus = getHealthStatus(healthScore)

    // 绘制主要统计数据（排便次数和健康评分）
    const statsY = dateY + padding * 2
    const statsBoxHeight = height * 0.2
    const statsBoxWidth = (width - padding * 3) / 2

    // 绘制左侧统计框（排便次数）
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.fillRect(padding, statsY, statsBoxWidth, statsBoxHeight)
    
    // 绘制右侧统计框（健康评分）
    ctx.fillRect(width - padding - statsBoxWidth, statsY, statsBoxWidth, statsBoxHeight)

    // 绘制排便次数
    ctx.textAlign = 'center'
    ctx.fillStyle = '#10b981'
    ctx.font = `bold ${Math.floor(width * 0.15)}px sans-serif`
    ctx.fillText(weekRecords.length.toString(), padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#333333'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText('本周排便次数', padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制健康评分
    ctx.fillStyle = healthStatus.color
    ctx.font = `bold ${Math.floor(width * 0.15)}px sans-serif`
    ctx.fillText(healthScore.toString(), width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#333333'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText('健康评分 · ' + healthStatus.text, width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制时间分布柱状图
    const chartY = height - padding * 4 - height * 0.25
    const chartHeight = height * 0.25
    const chartWidth = width - padding * 2.4
    
    // 定义时间段
    const timeGroups = [
      { name: '凌晨', color: '#fcd34d', count: 0 },  // 橙黄色（不太健康的时间）
      { name: '早上', color: '#4ade80', count: 0 },  // 翠绿色（最健康的时间）
      { name: '中午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '下午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '晚上', color: '#fcd34d', count: 0 }   // 橙黄色（不太健康的时间）
    ]

    // 统计各时间段的数量
    weekRecords.forEach(record => {
      const hour = new Date(record.date + ' ' + record.time).getHours()
      if (hour >= 0 && hour < 6) timeGroups[0].count++
      else if (hour >= 6 && hour < 11) timeGroups[1].count++
      else if (hour >= 11 && hour < 14) timeGroups[2].count++
      else if (hour >= 14 && hour < 18) timeGroups[3].count++
      else timeGroups[4].count++
    })

    // 找出最大值
    const maxCount = Math.max(...timeGroups.map(g => g.count), 1)

    // 绘制图表背景
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.fillRect(padding, chartY - padding, width - padding * 2, chartHeight + padding * 2)

    // 绘制柱状图
    const barWidth = chartWidth / timeGroups.length * 0.6
    const barGap = chartWidth / timeGroups.length

    // 绘制网格线
    ctx.strokeStyle = '#e6e6e6'
    ctx.lineWidth = 1
    for (let i = 0; i <= 4; i++) {
      const y = chartY + chartHeight * (1 - i / 4)
      ctx.beginPath()
      ctx.moveTo(padding * 1.2, y)
      ctx.lineTo(width - padding * 1.2, y)
      ctx.stroke()
    }

    timeGroups.forEach((group, index) => {
      const barHeight = (group.count / maxCount) * chartHeight
      const x = padding * 1.2 + barGap * index + (barGap - barWidth) / 2
      const y = chartY + chartHeight - barHeight

      // 绘制柱子
      ctx.fillStyle = group.color
      ctx.beginPath()
      const radius = barWidth * 0.15
      ctx.moveTo(x + radius, y)
      ctx.lineTo(x + barWidth - radius, y)
      ctx.quadraticCurveTo(x + barWidth, y, x + barWidth, y + radius)
      ctx.lineTo(x + barWidth, y + barHeight - radius)
      ctx.quadraticCurveTo(x + barWidth, y + barHeight, x + barWidth - radius, y + barHeight)
      ctx.lineTo(x + radius, y + barHeight)
      ctx.quadraticCurveTo(x, y + barHeight, x, y + barHeight - radius)
      ctx.lineTo(x, y + radius)
      ctx.quadraticCurveTo(x, y, x + radius, y)
      ctx.closePath()
      ctx.fill()

      // 添加渐变效果
      const gradient = ctx.createLinearGradient(x, y, x, y + barHeight)
      gradient.addColorStop(0, group.color)
      gradient.addColorStop(1, group.color + 'aa')
      ctx.fillStyle = gradient
      ctx.fill()

      // 绘制数值
      if (group.count > 0) {
        ctx.fillStyle = '#6b4f3f'
        ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
        ctx.textAlign = 'center'
        ctx.fillText(group.count, x + barWidth / 2, y - 10)
      }

      // 绘制标签（时间段）
      ctx.fillStyle = '#6b4f3f'
      ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
      ctx.textAlign = 'center'
      ctx.strokeStyle = '#fff9e9'
      ctx.lineWidth = 3
      ctx.strokeText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
      ctx.fillText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
    })

    // 绘制图表标题
    ctx.fillStyle = '#6b4f3f'
    ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText('时间分布', width / 2, chartY + chartHeight + 60)

    // 绘制装饰性图标
    this.drawDecorativeElements(ctx, width, height, padding)
  },

  // 绘制月报
  async drawMonthlyReport(ctx) {
    const width = ctx._width
    const height = ctx._height
    const padding = width * 0.08
    
    // 绘制背景
    ctx.fillStyle = '#e8f4f8'  // 使用浅蓝色背景
    ctx.fillRect(0, 0, width, height)
    
    // 绘制主卡片背景
    const cardPadding = padding * 0.5
    ctx.fillStyle = '#ffffff'
    this.drawRoundedRect(ctx, cardPadding, cardPadding, width - cardPadding * 2, height - cardPadding * 2, 20)
    ctx.fill()
    
    // 绘制标题
    const titleY = padding * 1.5
    const gradient = ctx.createLinearGradient(0, titleY - 30, 0, titleY)
    gradient.addColorStop(0, '#ff9a9e')
    gradient.addColorStop(1, '#fad0c4')
    ctx.fillStyle = gradient
    ctx.font = `bold ${Math.floor(width * 0.1)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText(this.data.reportTitle, width / 2, titleY)

    // 获取本月日期范围
    const today = new Date()
    const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)
    const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0)

    // 绘制日期范围
    const dateY = titleY + padding * 0.8
    ctx.fillStyle = '#666666'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText(`${this.formatDate(monthStart)} 至 ${this.formatDate(monthEnd)}`, width / 2, dateY)

    // 获取本月数据
    const monthRecords = (app.globalData.records || []).filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= monthStart && recordDate <= monthEnd
    })

    // 计算健康评分
    const healthScore = calculateHealthScore(monthRecords)
    const healthStatus = getHealthStatus(healthScore)

    // 绘制主要统计数据（排便次数和健康评分）
    const statsY = dateY + padding * 2
    const statsBoxHeight = height * 0.2
    const statsBoxWidth = (width - padding * 3) / 2

    // 绘制左侧统计框（排便次数）
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.fillRect(padding, statsY, statsBoxWidth, statsBoxHeight)
    
    // 绘制右侧统计框（健康评分）
    ctx.fillRect(width - padding - statsBoxWidth, statsY, statsBoxWidth, statsBoxHeight)

    // 绘制排便次数
    ctx.textAlign = 'center'
    ctx.fillStyle = '#10b981'
    ctx.font = `bold ${Math.floor(width * 0.15)}px sans-serif`
    ctx.fillText(monthRecords.length.toString(), padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#333333'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText('本月排便次数', padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制健康评分
    ctx.fillStyle = healthStatus.color
    ctx.font = `bold ${Math.floor(width * 0.15)}px sans-serif`
    ctx.fillText(healthScore.toString(), width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#333333'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText('健康评分 · ' + healthStatus.text, width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制时间分布柱状图（与日报相同的代码）
    const chartY = height - padding * 4 - height * 0.25
    const chartHeight = height * 0.25
    const chartWidth = width - padding * 2.4
    
    // 定义时间段
    const timeGroups = [
      { name: '凌晨', color: '#fcd34d', count: 0 },  // 橙黄色（不太健康的时间）
      { name: '早上', color: '#4ade80', count: 0 },  // 翠绿色（最健康的时间）
      { name: '中午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '下午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '晚上', color: '#fcd34d', count: 0 }   // 橙黄色（不太健康的时间）
    ]

    // 统计各时间段的数量
    monthRecords.forEach(record => {
      const hour = new Date(record.date + ' ' + record.time).getHours()
      if (hour >= 0 && hour < 6) timeGroups[0].count++
      else if (hour >= 6 && hour < 11) timeGroups[1].count++
      else if (hour >= 11 && hour < 14) timeGroups[2].count++
      else if (hour >= 14 && hour < 18) timeGroups[3].count++
      else timeGroups[4].count++
    })

    // 找出最大值
    const maxCount = Math.max(...timeGroups.map(g => g.count), 1)

    // 绘制图表背景
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.fillRect(padding, chartY - padding, width - padding * 2, chartHeight + padding * 2)

    // 绘制柱状图
    const barWidth = chartWidth / timeGroups.length * 0.6
    const barGap = chartWidth / timeGroups.length

    // 绘制网格线
    ctx.strokeStyle = '#e6e6e6'
    ctx.lineWidth = 1
    for (let i = 0; i <= 4; i++) {
      const y = chartY + chartHeight * (1 - i / 4)
      ctx.beginPath()
      ctx.moveTo(padding * 1.2, y)
      ctx.lineTo(width - padding * 1.2, y)
      ctx.stroke()
    }

    timeGroups.forEach((group, index) => {
      const barHeight = (group.count / maxCount) * chartHeight
      const x = padding * 1.2 + barGap * index + (barGap - barWidth) / 2
      const y = chartY + chartHeight - barHeight

      // 绘制柱子
      ctx.fillStyle = group.color
      ctx.beginPath()
      const radius = barWidth * 0.15
      ctx.moveTo(x + radius, y)
      ctx.lineTo(x + barWidth - radius, y)
      ctx.quadraticCurveTo(x + barWidth, y, x + barWidth, y + radius)
      ctx.lineTo(x + barWidth, y + barHeight - radius)
      ctx.quadraticCurveTo(x + barWidth, y + barHeight, x + barWidth - radius, y + barHeight)
      ctx.lineTo(x + radius, y + barHeight)
      ctx.quadraticCurveTo(x, y + barHeight, x, y + barHeight - radius)
      ctx.lineTo(x, y + radius)
      ctx.quadraticCurveTo(x, y, x + radius, y)
      ctx.closePath()
      ctx.fill()

      // 添加渐变效果
      const gradient = ctx.createLinearGradient(x, y, x, y + barHeight)
      gradient.addColorStop(0, group.color)
      gradient.addColorStop(1, group.color + 'aa')
      ctx.fillStyle = gradient
      ctx.fill()

      // 绘制数值
      if (group.count > 0) {
        ctx.fillStyle = '#6b4f3f'
        ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
        ctx.textAlign = 'center'
        ctx.fillText(group.count, x + barWidth / 2, y - 10)
      }

      // 绘制标签（时间段）
      ctx.fillStyle = '#6b4f3f'
      ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
      ctx.textAlign = 'center'
      ctx.strokeStyle = '#fff9e9'
      ctx.lineWidth = 3
      ctx.strokeText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
      ctx.fillText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
    })

    // 绘制图表标题
    ctx.fillStyle = '#6b4f3f'
    ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText('时间分布', width / 2, chartY + chartHeight + 60)

    // 绘制装饰性图标
    this.drawDecorativeElements(ctx, width, height, padding)
  },

  // 绘制年报
  async drawYearlyReport(ctx) {
    const width = ctx._width
    const height = ctx._height
    const padding = width * 0.08
    
    // 绘制背景
    ctx.fillStyle = '#e8f4f8'  // 使用浅蓝色背景
    ctx.fillRect(0, 0, width, height)
    
    // 绘制主卡片背景
    const cardPadding = padding * 0.5
    ctx.fillStyle = '#ffffff'
    this.drawRoundedRect(ctx, cardPadding, cardPadding, width - cardPadding * 2, height - cardPadding * 2, 20)
    ctx.fill()
    
    // 绘制标题
    const titleY = padding * 1.5
    const gradient = ctx.createLinearGradient(0, titleY - 30, 0, titleY)
    gradient.addColorStop(0, '#ff9a9e')
    gradient.addColorStop(1, '#fad0c4')
    ctx.fillStyle = gradient
    ctx.font = `bold ${Math.floor(width * 0.1)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText(this.data.reportTitle, width / 2, titleY)

    // 获取本年日期范围
    const today = new Date()
    const yearStart = new Date(today.getFullYear(), 0, 1)
    const yearEnd = new Date(today.getFullYear(), 11, 31)

    // 绘制日期范围
    const dateY = titleY + padding * 0.8
    ctx.fillStyle = '#666666'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText(`${this.formatDate(yearStart)} 至 ${this.formatDate(yearEnd)}`, width / 2, dateY)

    // 获取本年数据
    const yearRecords = (app.globalData.records || []).filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= yearStart && recordDate <= yearEnd
    })

    // 计算健康评分
    const healthScore = calculateHealthScore(yearRecords)
    const healthStatus = getHealthStatus(healthScore)

    // 绘制主要统计数据（排便次数和健康评分）
    const statsY = dateY + padding * 2
    const statsBoxHeight = height * 0.2
    const statsBoxWidth = (width - padding * 3) / 2

    // 绘制左侧统计框（排便次数）
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.fillRect(padding, statsY, statsBoxWidth, statsBoxHeight)
    
    // 绘制右侧统计框（健康评分）
    ctx.fillRect(width - padding - statsBoxWidth, statsY, statsBoxWidth, statsBoxHeight)

    // 绘制排便次数
    ctx.textAlign = 'center'
    ctx.fillStyle = '#10b981'
    ctx.font = `bold ${Math.floor(width * 0.15)}px sans-serif`
    ctx.fillText(yearRecords.length.toString(), padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#333333'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText('本年排便次数', padding + statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制健康评分
    ctx.fillStyle = healthStatus.color
    ctx.font = `bold ${Math.floor(width * 0.15)}px sans-serif`
    ctx.fillText(healthScore.toString(), width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.45)
    
    ctx.fillStyle = '#333333'
    ctx.font = `${Math.floor(width * 0.05)}px sans-serif`
    ctx.fillText('健康评分 · ' + healthStatus.text, width - padding - statsBoxWidth / 2, statsY + statsBoxHeight * 0.75)

    // 绘制时间分布柱状图（与日报相同的代码）
    const chartY = height - padding * 4 - height * 0.25
    const chartHeight = height * 0.25
    const chartWidth = width - padding * 2.4
    
    // 定义时间段
    const timeGroups = [
      { name: '凌晨', color: '#fcd34d', count: 0 },  // 橙黄色（不太健康的时间）
      { name: '早上', color: '#4ade80', count: 0 },  // 翠绿色（最健康的时间）
      { name: '中午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '下午', color: '#86efac', count: 0 },  // 浅绿色（健康的时间）
      { name: '晚上', color: '#fcd34d', count: 0 }   // 橙黄色（不太健康的时间）
    ]

    // 统计各时间段的数量
    yearRecords.forEach(record => {
      const hour = new Date(record.date + ' ' + record.time).getHours()
      if (hour >= 0 && hour < 6) timeGroups[0].count++
      else if (hour >= 6 && hour < 11) timeGroups[1].count++
      else if (hour >= 11 && hour < 14) timeGroups[2].count++
      else if (hour >= 14 && hour < 18) timeGroups[3].count++
      else timeGroups[4].count++
    })

    // 找出最大值
    const maxCount = Math.max(...timeGroups.map(g => g.count), 1)

    // 绘制图表背景
    ctx.fillStyle = 'rgba(255, 255, 255, 0.9)'
    ctx.fillRect(padding, chartY - padding, width - padding * 2, chartHeight + padding * 2)

    // 绘制柱状图
    const barWidth = chartWidth / timeGroups.length * 0.6
    const barGap = chartWidth / timeGroups.length

    // 绘制网格线
    ctx.strokeStyle = '#e6e6e6'
    ctx.lineWidth = 1
    for (let i = 0; i <= 4; i++) {
      const y = chartY + chartHeight * (1 - i / 4)
      ctx.beginPath()
      ctx.moveTo(padding * 1.2, y)
      ctx.lineTo(width - padding * 1.2, y)
      ctx.stroke()
    }

    timeGroups.forEach((group, index) => {
      const barHeight = (group.count / maxCount) * chartHeight
      const x = padding * 1.2 + barGap * index + (barGap - barWidth) / 2
      const y = chartY + chartHeight - barHeight

      // 绘制柱子
      ctx.fillStyle = group.color
      ctx.beginPath()
      const radius = barWidth * 0.15
      ctx.moveTo(x + radius, y)
      ctx.lineTo(x + barWidth - radius, y)
      ctx.quadraticCurveTo(x + barWidth, y, x + barWidth, y + radius)
      ctx.lineTo(x + barWidth, y + barHeight - radius)
      ctx.quadraticCurveTo(x + barWidth, y + barHeight, x + barWidth - radius, y + barHeight)
      ctx.lineTo(x + radius, y + barHeight)
      ctx.quadraticCurveTo(x, y + barHeight, x, y + barHeight - radius)
      ctx.lineTo(x, y + radius)
      ctx.quadraticCurveTo(x, y, x + radius, y)
      ctx.closePath()
      ctx.fill()

      // 添加渐变效果
      const gradient = ctx.createLinearGradient(x, y, x, y + barHeight)
      gradient.addColorStop(0, group.color)
      gradient.addColorStop(1, group.color + 'aa')
      ctx.fillStyle = gradient
      ctx.fill()

      // 绘制数值
      if (group.count > 0) {
        ctx.fillStyle = '#6b4f3f'
        ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
        ctx.textAlign = 'center'
        ctx.fillText(group.count, x + barWidth / 2, y - 10)
      }

      // 绘制标签（时间段）
      ctx.fillStyle = '#6b4f3f'
      ctx.font = `bold ${Math.floor(width * 0.045)}px sans-serif`
      ctx.textAlign = 'center'
      ctx.strokeStyle = '#fff9e9'
      ctx.lineWidth = 3
      ctx.strokeText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
      ctx.fillText(group.name, x + barWidth / 2, chartY + chartHeight + 25)
    })

    // 绘制图表标题
    ctx.fillStyle = '#6b4f3f'
    ctx.font = `${Math.floor(width * 0.045)}px sans-serif`
    ctx.textAlign = 'center'
    ctx.fillText('时间分布', width / 2, chartY + chartHeight + 60)

    // 绘制装饰性图标
    this.drawDecorativeElements(ctx, width, height, padding)
  },
})